<script setup>
import { ref, onMounted, watch } from 'vue'
import { fileListService } from '@/api/file'
import { uploadFileService } from '@/api/file'
// 新增删除接口导入（需确保后端存在对应接口）
import { fileDeleteService } from '@/api/file'
import { ElMessage, ElTable, ElTableColumn, ElCard, ElPagination, ElDrawer, ElForm, ElUpload, ElButton, ElSelect, ElOption, ElInput, ElMessageBox } from 'element-plus'
// 新增查看和删除图标
import { Upload, Calendar, Plus, View, Delete } from '@element-plus/icons-vue'

// 存储文件列表数据
const fileList = ref([])
// 加载状态
const loading = ref(false)

// 分页相关状态
const currentPage = ref(1) // 当前页码（默认第一页）
const pageSize = ref(5)    // 每页条数（默认5条）
const total = ref(0)       // 总数据条数

// 抽屉相关状态
const drawer = ref(false)
const direction = ref('rtl')

// 上传表单数据
const formData = ref({
  file: null,
  type: '',
  area: '',
  date: '',
  fileDesc: ''
})

// 控制区域输入框的显示与隐藏
const showArea = ref(false)
const formRef = ref(null)

// 监听type变化，控制area的显示
watch(
    () => formData.value.type,
    (newVal) => {
      showArea.value = newVal === 'drone'
      if (!showArea.value) {
        formData.value.area = ''
      }
    }
)

// 表单验证规则
const rules = {
  file: [
    { required: true, message: '请选择要上传的文件', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择数据类型', trigger: 'change' }
  ],
  area: [
    { required: showArea.value, message: '请输入区域信息', trigger: 'blur' }
  ],
  fileDesc: [
    { max: 200, message: '文件描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取文件列表（适配新返回格式）
// const getFileList = async () => {
//   try {
//     loading.value = true
//     // 传递接口要求的 pageNum 和 pageSize 参数
//     const result = await fileListService({
//       pageNum: currentPage.value,
//       pageSize: pageSize.value
//     })
//
//     // 数据路径修正为 data.items（根据你的返回格式）
//     fileList.value = result.data.items
//     // 总条数路径修正为 data.total
//     total.value = result.data.total
//   } catch (error) {
//     ElMessage.error('获取文件列表失败')
//     console.error(error)
//   } finally {
//     loading.value = false
//   }
// }

// 页面加载时获取第一页数据
onMounted(() => {
  getFileList()
})

// 页码变化时触发
const handlePageChange = (page) => {
  currentPage.value = page
  getFileList()
}

// 每页条数变化时触发
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1 // 重置为第一页
  getFileList()
}

// 处理文件上传
const handleUpload = async () => {
  // 表单验证
  const valid = await formRef.value.validate()
  if (!valid) return

  // 创建FormData对象
  const data = new FormData()
  data.append('file', formData.value.file)
  data.append('type', formData.value.type)

  // 只有无人机类型才添加area参数
  if (showArea.value && formData.value.area) {
    data.append('area', formData.value.area)
  }

  data.append('date', formData.value.date)
  if (formData.value.fileDesc) {
    data.append('fileDesc', formData.value.fileDesc)
  }
  try {
    await uploadFileService(data)
    ElMessage.success('文件上传成功')
    // 重置表单
    formRef.value.resetFields()
    formData.value.file = null
    drawer.value = false
    // 重新获取文件列表
    getFileList()
  } catch (error) {
    ElMessage.error('文件上传失败：' + (error.message || '未知错误'))
  }
}

// 新增查询表单数据
const queryForm = ref({
  area: '',
  date: ''
})

// 修改getFileList方法，添加查询参数
const getFileList = async () => {
  try {
    loading.value = true
    // 传递分页参数+查询条件
    const result = await fileListService({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      area: queryForm.value.area, // 新增区域参数
      date: queryForm.value.date  // 新增日期参数
    })

    fileList.value = result.data.items
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('获取文件列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 新增查询方法
const handleQuery = () => {
  currentPage.value = 1 // 重置为第一页
  getFileList()
}

// 新增重置方法
const resetQuery = () => {
  queryForm.value = {
    area: '',
    date: ''
  }
  currentPage.value = 1
  getFileList()
}
// 处理文件选择
const handleFileChange = (uploadFile) => {
  // 验证文件类型是否为zip
  if (uploadFile.raw && !uploadFile.name.endsWith('.zip')) {
    ElMessage.error('请上传zip格式的文件')
    formData.value.file = null
    return
  }
  formData.value.file = uploadFile.raw
}

// 关闭抽屉时重置表单
const handleCloseDrawer = () => {
  formRef.value.resetFields()
  formData.value.file = null
  drawer.value = false
}


// 删除文件方法
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '你确认要删除该文件吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      // 调用文件删除接口
      await fileDeleteService(row.id)
      ElMessage.success('删除成功')
      // 重新获取文件列表
      getFileList()
    } catch (error) {
      ElMessage.error('删除失败：' + (error.message || '未知错误'))
    }
  })
}
const detailDrawer = ref(false)
const currentFile = ref({})

// 修改查看文件方法
const handleView = (row) => {
  // 设置当前查看的文件信息
  currentFile.value = { ...row }
  // 打开详情抽屉
  detailDrawer.value = true
}
const areaMap = {
  hadawan: '哈达湾',
  niaodao: '鸟岛',
  buhahekouhaibeiqu: '布哈河口海北区',
  buhahekouhainanqu: '布哈河口海南区',
  quanwan: '泉湾',
  heimahekou: '黑马河口',
  shaliuhekou: '沙柳河口',
  quanjihekou: '泉吉河口',
  erlangjian: '二郎剑',
  yilangjianzihu: '一郎剑子湖',
  erhai: '洱海',
  qinghaihu: '青海湖'
}

// 关闭详情抽屉
const handleCloseDetailDrawer = () => {
  detailDrawer.value = false
}
const formatAreaName = (pinyin) => {
  return areaMap[pinyin] || pinyin
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>文件管理</span>
        <el-button type="primary" :icon="Plus" @click="drawer = true">
          上传文件
        </el-button>
      </div>
    </template>
    <!-- 新增查询表单 -->
    <el-form inline :model="queryForm" class="query-form" style="margin-bottom: 20px;">
      <el-form-item label="区域">
        <el-select v-model="queryForm.area" placeholder="请选择区域">
          <el-option label="哈达湾" value="hadawan"></el-option>
          <el-option label="鸟岛" value="niaodao"></el-option>
          <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
          <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
          <el-option label="泉湾" value="quanwan"></el-option>
          <el-option label="黑马河口" value="heimahekou"></el-option>
          <el-option label="沙柳河口" value="shaliuhekou"></el-option>
          <el-option label="泉吉河口" value="quanjihekou"></el-option>
          <el-option label="二郎剑" value="erlangjian"></el-option>
          <el-option label="一郎剑子湖" value="yilangjianzihu"></el-option>
          <el-option label="洱海" value="erhai"></el-option>
          <el-option label="青海湖" value="qinghaihu"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="日期">
        <el-date-picker
            v-model="queryForm.date"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
            :prefix-icon="Calendar"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table
        v-loading="loading"
        :data="fileList"
        border
        style="width: 100%; margin-bottom: 20px"
    >
      <el-table-column
          prop="id"
          label="文件ID"
          width="100"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="type"
          label="文件类型"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="area"
          label="所属区域"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="date"
          label="上传日期"
          width="180"
          align="center"
      ></el-table-column>
      <!-- 新增操作时间列（对应 optionTime 字段） -->
      <el-table-column
          prop="operationTime"
          label="操作时间"
          width="180"
          align="center"
      ></el-table-column>
      <el-table-column
          label="操作"
          width="200"
          align="center"
      >
        <template #default="scope">
          <!-- 修改为圆形图标按钮，与ArticleManage保持一致 -->
          <el-button :icon="View" circle plain type="primary" @click="handleView(scope.row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>

    <!-- 上传文件抽屉 -->
    <el-drawer
        v-model="drawer"
        title="文件上传"
        :direction="direction"
        :before-close="handleCloseDrawer"
        size="50%"
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          size="large"
      >
        <!-- 文件上传 -->
        <el-form-item label="选择文件" prop="file">
          <el-upload
              class="upload-demo"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleFileChange"
              accept=".zip"
          >
            <el-button type="primary" :icon="Upload">选择ZIP文件</el-button>
            <div class="el-upload__text">支持上传.zip格式文件</div>
          </el-upload>
          <div v-if="formData.file" class="file-name">
            已选择: {{ formData.file.name }}
          </div>
        </el-form-item>

        <!-- 类型选择 -->
        <el-form-item label="数据类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择数据类型">
              <el-option label="卫星" value="satellite"></el-option>
              <el-option label="无人机" value="drone"></el-option>
          </el-select>
        </el-form-item>

        <!-- 区域输入（条件显示） -->
        <el-form-item v-if="showArea" label="区域" prop="area">
          <el-select v-model="formData.area" placeholder="请选择区域">
            <el-option label="哈达湾" value="hadawan"></el-option>
            <el-option label="鸟岛" value="niaodao"></el-option>
            <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
            <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
            <el-option label="泉湾" value="quanwan"></el-option>
            <el-option label="黑马河口" value="heimahekou"></el-option>
            <el-option label="沙柳河口" value="shaliuhekou"></el-option>
            <el-option label="泉吉河口" value="quanjihekou"></el-option>
            <el-option label="二郎剑" value="erlangjian"></el-option>
            <el-option label="一郎剑子湖" value="yilangjianzihu"></el-option>
            <el-option label="洱海" value="erhai"></el-option>
          </el-select>
        </el-form-item>

        <!-- 日期输入 -->
        <el-form-item label="日期" prop="date">
          <el-date-picker
              v-model="formData.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择数据采集时间"
              :prefix-icon="Calendar"
          ></el-date-picker>
        </el-form-item><el-form-item label="文件描述" prop="fileDesc">
        <el-input
            v-model="formData.fileDesc"
            placeholder="可选，说明文件内容（如“2024年9月西湖卫星影像”）"
            maxlength="200"
           ></el-input>
         </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" size="large" @click="handleUpload">
            上传文件
          </el-button>
          <el-button size="large" @click="handleCloseDrawer" style="margin-left: 10px">
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer
        v-model="detailDrawer"
        title="文件详情"
        direction="rtl"
        size="50%"
        :before-close="handleCloseDetailDrawer"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="文件ID">{{ currentFile.id }}</el-descriptions-item>
<!--        <el-descriptions-item label="文件名称">{{ currentFile.fileName }}</el-descriptions-item>-->
        <el-descriptions-item label="文件类型">
          {{ currentFile.type === 'satellite' ? '卫星' : '无人机' }}
        </el-descriptions-item>
        <el-descriptions-item label="所属区域">{{ formatAreaName(currentFile.area) }}</el-descriptions-item>
        <el-descriptions-item label="上传日期">{{ currentFile.date }}</el-descriptions-item>
        <el-descriptions-item label="操作时间">{{ currentFile.operationTime }}</el-descriptions-item>
        <el-descriptions-item label="文件描述">{{ currentFile.fileDesc || '无描述信息' }}</el-descriptions-item>
        <el-descriptions-item label="文件大小">
          {{ currentFile.fileSize ? (currentFile.fileSize / 1024 / 1024).toFixed(2) + ' MB' : '未知' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </el-card>
</template>

<style scoped>
.page-container {
  margin: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.file-name {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
  word-break: break-all;
}
.query-form {
  padding: 10px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding-left: 16px;
  margin-bottom: 20px;
}
</style>